package com.luoxiang.socialandroid.fragment;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.DOMAIN;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.GENDER;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.HOSTAUDIT;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CHECKSUM;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_CURRTIME;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY_NONCE;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.activity.DetailsActivity;
import com.luoxiang.socialandroid.activity.OnlineMatchingActivity;
import com.luoxiang.socialandroid.activity.VedioActivity;
import com.luoxiang.socialandroid.activity.YouxuanActivity;
import com.luoxiang.socialandroid.adapter.TuijianRecyAdapter;
import com.luoxiang.socialandroid.adapter.YouxuanRecyAdapter;
import com.luoxiang.socialandroid.base.LazyLoadFragment;
import com.luoxiang.socialandroid.bean.BannerBean;
import com.luoxiang.socialandroid.bean.Broadcasts;
import com.luoxiang.socialandroid.bean.HostBean;
import com.luoxiang.socialandroid.bean.MineInfoBean;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.TopRecommendBean;
import com.luoxiang.socialandroid.bean.TypehostBean;
import com.luoxiang.socialandroid.bean.YouxuanBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.LoopUtil;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnLoadMoreListener;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.stx.xhb.xbanner.XBanner;
import com.stx.xhb.xbanner.transformers.Transformer;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import kotlin.random.Random;

public class TuijianFragment extends LazyLoadFragment {

    private String url = "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/";
    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private String token;
    private XBanner xb;
    private TextView tx_youxuan, textRecommendExpire, textBannerContent;
    private RecyclerView rc_youxuan, rc_tuijian;
    private YouxuanRecyAdapter youxuanRecyAdapter;
    private TuijianRecyAdapter tuijianRecyAdapter;
    private SmartRefreshLayout smartRefreshLayout;
    private ImageView imageRecommend;
    private int page = 1;
    private List<HostBean> list;
    private ImageView img_loading;
    private RelativeLayout relaToCallUser;
    private ImageView img_guanbizhege;
    private int gender;
    private int host;
    private LinearLayout linearBannerText;
    private ConstraintLayout constraintRecommend;
    private LoopUtil loopUtil;

    @Override
    protected int setContentView() {
        return R.layout.fragment_tuijian;
    }


    @Override
    protected void initView() {
        loopUtil = new LoopUtil(this);
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        list = new ArrayList<>();
        xb = findViewById(R.id.banner);
        rc_youxuan = findViewById(R.id.rc_youxuan);
        rc_tuijian = findViewById(R.id.rc_tuijian);
        tx_youxuan = findViewById(R.id.tx_youxuan);
        imageRecommend = findViewById(R.id.imageRecommend);
        relaToCallUser = findViewById(R.id.relaToCallUser);
        smartRefreshLayout = findViewById(R.id.smartRefresh);
        img_guanbizhege = findViewById(R.id.img_guanbizhege);
        textRecommendExpire = findViewById(R.id.textRecommendExpire);
        linearBannerText = findViewById(R.id.linearBannerText);
        constraintRecommend = findViewById(R.id.constraintRecommend);
        textBannerContent = findViewById(R.id.textBannerContent);
        Integer host = MmkvUtil.INSTANCE.decodeInt(HOSTAUDIT);
        if (host != null && host == 1) {
            linearBannerText.setVisibility(View.VISIBLE);
            constraintRecommend.setVisibility(View.VISIBLE);
        } else {
            linearBannerText.setVisibility(View.GONE);
            constraintRecommend.setVisibility(View.GONE);
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 2, GridLayoutManager.VERTICAL, false);
        rc_tuijian.setLayoutManager(gridLayoutManager);
        tuijianRecyAdapter = new TuijianRecyAdapter();
        rc_tuijian.setAdapter(tuijianRecyAdapter);
        smartRefreshLayout.setEnableRefresh(true);
        smartRefreshLayout.setEnableLoadMore(true);
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                getRequest();
//                getbanner(token, EXTRA);
                getTitleHosts(token, EXTRA);
                getTypeHosts(token, EXTRA, 0, page, "10");
                getHomeUserInfo(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                page++;
                getTypeHosts(token, EXTRA, 0, page, "10");
            }
        });
        xb.startAutoPlay();
        toyouxuan();
        rc_tuijian.setNestedScrollingEnabled(false);
    }

    private void getHomeUserInfo(String token, String extra) {
        NetUtils2.getInstance().getApiService().getHomeUserInfo(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new io.reactivex.Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                            LogUtils.i("decryptStr0", decryptStr);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Gson gson = new Gson();
                            MineInfoBean bean = gson.fromJson(decryptStr, MineInfoBean.class);
                            if (bean != null) {
                                if (bean.getData() != null) {
                                    if (bean.getData().getUser() != null) {
                                        gender = bean.getData().getUser().getGender();
                                        host = bean.getData().getUser().getHost();

                                    }
                                }
                            }
                        } catch (Exception e) {
                            LogUtils.e("decryptStr0", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        LogUtils.i("xx", e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void toyouxuan() {
        tx_youxuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getActivity(), YouxuanActivity.class);
                startActivity(intent);
            }
        });
        relaToCallUser.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                if (gender == 0 && host == 0) {
                    //表示是女并且不是主播
                    ToastUtils.showShort("认证成为主播后可使用该功能");
                    return;
                } else {
                    initScreenRecorderBuild();
                }


            }

            @Override
            protected void onFastClick() {

            }
        });
        img_guanbizhege.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                relaToCallUser.setVisibility(View.GONE);
            }

            @Override
            protected void onFastClick() {

            }
        });
        imageRecommend.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                topRecommend();
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    private void topRecommend() {
        getRequest();
        NetUtils.getInstance().getApiService().topRecommend(EXTRA, MmkvUtil.INSTANCE.decodeString(TOKEN))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean value) {
                        String data = value.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        TopRecommendBean topRecommendBean = gson.fromJson(decryptStr, TopRecommendBean.class);
                        if (topRecommendBean.getData() != null) {
                            smartRefreshLayout.autoRefresh();
                            initRecommendUI(topRecommendBean.getData().getRecommendExpire());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(getActivity());
        rxPermissions.request(
                Manifest.permission.RECORD_AUDIO,
                Manifest.permission.CAMERA


        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    Intent intent = new Intent(requireContext(), OnlineMatchingActivity.class);
                    startActivity(intent);
                } else {
                    ToastUtils.showShort(R.string.mi_camera_video_quanxian);
                }
            }
        });
    }

    @Override
    protected void lazyLoad() {
        showLoading();
        getbanner(token, EXTRA);
        getTitleHosts(token, EXTRA);
        getHomeUserInfo(MmkvUtil.INSTANCE.decodeString(TOKEN), EXTRA);
        getTypeHosts(token, EXTRA, 0, page, "10");
    }


    /**
     * 推荐接口调用
     *
     * @param token
     * @param extra
     * @param i
     */
    private void getTypeHosts(String token, String extra, int i, int page, String limit) {
        getRequest();
        NetUtils2.getInstance().getApiService().getTypeHosts2(token, extra, "0", page, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();

                        TypehostBean bean = gson.fromJson(decryptStr, TypehostBean.class);

                        if (bean != null) {
                            if (bean.getData() != null) {

                                tuijianRecyAdapter.setOnAddClickListener(new TuijianRecyAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(int position, int userid, int covertype, String name, String icon, String cover, String videoPath) {
                                        if (covertype == 0) {
                                            //跳转图片
                                            Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                            intent.putExtra("userid", userid);
                                            startActivity(intent);
                                        } else {
                                            //跳转视频
                                            Intent intent = new Intent(getActivity(), VedioActivity.class);
                                            intent.putExtra("userid", userid);
                                            intent.putExtra("username", name);
                                            intent.putExtra("usericon", icon);
                                            intent.putExtra("urls", DOMAIN + videoPath);
                                            startActivity(intent);
                                        }
                                    }
                                });
                                if (list != null) {
                                    if (page == 1) {
                                        list.clear();
                                    }
                                }


                                if (bean.getData() != null && bean.getData().getHosts() != null && bean.getData().getHosts().size() > 0) {
                                    if (list != null) {
                                        list.addAll(bean.getData().getHosts());
                                    }
                                    tuijianRecyAdapter.setData(list);
                                    tuijianRecyAdapter.notifyDataSetChanged();
                                } else {
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {
                        if (smartRefreshLayout != null) {
                            smartRefreshLayout.finishRefresh();
                            smartRefreshLayout.finishLoadMore();
                        }
                    }
                });
    }

    /**
     * 优选接口调用
     *
     * @param token
     * @param extra
     */
    private void getTitleHosts(String token, String extra) {
        NetUtils2.getInstance().getApiService().getTitleHosts(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        YouxuanBean bean = gson.fromJson(decryptStr, YouxuanBean.class);
                        if (bean == null || bean.getData() == null) return;

                        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
                        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
                        rc_youxuan.setLayoutManager(layoutManager);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                initRecommendUI(bean.getData().getRecommendExpire());
                                youxuanRecyAdapter = new YouxuanRecyAdapter(bean.getData().getHosts());
                                rc_youxuan.setAdapter(youxuanRecyAdapter);
                                youxuanRecyAdapter.setOnAddClickListener(new YouxuanRecyAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(int position, int userid, String videoPath) {
                                        if (bean.getData().getHosts().get(position).getCoverType() == 0) {
                                            //跳转图片
                                            Intent intent = new Intent(getActivity(), DetailsActivity.class);
                                            intent.putExtra("userid", userid);
                                            startActivity(intent);
                                        } else {
                                            //跳转视频
                                            Intent intent = new Intent(getActivity(), VedioActivity.class);
                                            intent.putExtra("userid", userid);
                                            String icon = bean.getData().getHosts().get(position).getIcon();
                                            intent.putExtra("username", bean.getData().getHosts().get(position).getName());
                                            intent.putExtra("usericon", icon);
                                            intent.putExtra("urls", DOMAIN + videoPath);
                                            startActivity(intent);
                                        }
                                    }
                                });
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });
    }

    private void initRecommendUI(Integer recommendExpire) {
        if (recommendExpire == null || recommendExpire <= 0) {
            imageRecommend.setImageResource(R.mipmap.button_recommended_40);
            textRecommendExpire.setText("10分钟/次");
            textRecommendExpire.setTextColor(Color.parseColor("#EEEEEE"));
            imageRecommend.setEnabled(true);
            imageRecommend.setClickable(true);
            return;
        }
        imageRecommend.setImageResource(R.mipmap.button_recommende_40);
        textRecommendExpire.setTextColor(Color.parseColor("#FF0000"));
        imageRecommend.setEnabled(false);
        imageRecommend.setClickable(false);
        Observable.intervalRange(0, recommendExpire, 0, 1, TimeUnit.SECONDS)
                .map(aLong -> recommendExpire - aLong - 1).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Long>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Long value) {
                        String time = new SimpleDateFormat("mm:ss", Locale.CHINA).format(value * 1000);
                        textRecommendExpire.setText(time);
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                        initRecommendUI(null);
                    }
                });
    }

    private void getbanner(String token, String extra) {
        NetUtils2.getInstance().getApiService().getBanners(token, extra)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        BannerBean bean = gson.fromJson(decryptStr, BannerBean.class);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                startBannerContent(bean.getData().getBroadcasts());
                                if (xb != null) {
                                    xb.setData(bean.getData().getBanners(), null);
                                    xb.setmAdapter(new XBanner.XBannerAdapter() {
                                        @Override
                                        public void loadBanner(XBanner banner, View view, int position) {
                                            RequestOptions options = new RequestOptions()
                                                    .placeholder(R.mipmap.icon_error_banner)
                                                    .fallback(R.mipmap.icon_error_banner)
                                                    .error(R.mipmap.icon_error_banner);
                                            Glide.with(getActivity()).load(url + bean.getData().getBanners().get(position).getImg()).apply(options).into((ImageView) view);
                                            ImageView imageView = (ImageView) view;
                                            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                                        }
                                    });

                                    xb.setPageTransformer(Transformer.Default);
                                    xb.setPageChangeDuration(100);
                                }
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void startBannerContent(List<Broadcasts> broadcasts) {
        Integer gender = MmkvUtil.INSTANCE.decodeInt(GENDER);
        if (gender == null || gender == 1 || broadcasts == null || broadcasts.isEmpty()) {
            return;
        }
        loopUtil.startLoopJob(5 * 1000, () -> {
            textBannerContent.setText(broadcasts.get(Random.Default.nextInt(0, broadcasts.size())).getTitle());
            return null;
        });
    }


    @Override
    public void onStop() {
        super.onStop();
        xb.stopAutoPlay();
    }

    public void getRequest() {
        String apiKey = "17SgH6kkUNk8tyxjR6rbXEDiIR4P3nQh";//prod环境
        String nonce = (int) (Math.random() * 9000 + 1000) + "";//四位随机数
        String currTime = System.currentTimeMillis() + "";//当前时间戳
        String value = apiKey + nonce + currTime;
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance("sha1");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        messageDigest.update(value.getBytes());
        byte[] bytes = messageDigest.digest();

        //转换成16进制
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        String newCheckSum = buf.toString();
        MmkvUtil.INSTANCE.encode(KEY_NONCE, nonce);
        MmkvUtil.INSTANCE.encode(KEY_CURRTIME, currTime);
        MmkvUtil.INSTANCE.encode(KEY_CHECKSUM, newCheckSum);
    }

}
